package com.zaprk.controller;

import com.zaprk.exception.FindByIdNotFoundException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

/**
 * 全局统一异常处理控制器
 */
@ControllerAdvice
public class ExceptionController {

    @ExceptionHandler(Exception.class)
    @ResponseBody
    public Map<String, Object> globalException(Exception e){
        Integer code = 200;
        String msg = "";
        // 处理异常    获取异常的类型
        if (e instanceof FindByIdNotFoundException) {
            code = 500;
            msg = e.getMessage();
        }else {
            code = 501;
            msg = e.getMessage();
        }

        Map<String, Object> map = new HashMap<>();
        map.put("code", code);
        map.put("msg", msg);

        return map;
    }
}
